<template>
  <div v-loading="loading" class="container role-container" style="padding-left: 0">
    <el-row class="table-top" style="padding-left: 10px">
      <div class="left">
        <el-tag class="role-tag" size="medium" :effect="labelType === 'emp' ? 'dark' : 'plain'" @click="changeLabelTypeFun('emp')"> 员工角色分配 </el-tag>
        <el-tag class="role-tag" size="medium" :effect="labelType === 'fun' ? 'dark' : 'plain'" @click="changeLabelTypeFun('fun')"> 功能权限设置 </el-tag>
      </div>
      <div v-if="labelType === 'emp'" class="right">
        <el-input v-model="searchValue.name" style="width: 150px;margin-right: 10px" placeholder="请输入员工名称" clearable @input="searchNameFun" />
        <el-button v-permission="['90005']" type="primary" @click="addEmpFun">添加员工</el-button>
      </div>
    </el-row>

    <div class="role-content">
      <div v-permission="['90001']" class="role-left">
        <div
          v-for="item in roleTypeArr"
          :key="item.name"
          :class=" item.name === activeType ? 'role-type active' : 'role-type'"
        >
          <span class="name" @click="changeRoleTypeFun(item)">{{ item.name }}</span>
          <el-dropdown trigger="click" @click.stop @command="handleCommand">
            <span class="el-dropdown-link">
              <div class="dian">...</div>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-permission="['90003']" :command="beforeHandleCommand('edit', item)" icon="el-icon-plus"> 编辑 </el-dropdown-item>
              <el-dropdown-item v-if="!item.is_built_in" v-permission="['90004']" :command="beforeHandleCommand('del', item)" icon="el-icon-circle-plus"> 删除 </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-popover
            placement="bottom"
            width="80"
            trigger="click"
            popper-class="popper-class"
          >
            <div class="popper-p">
              <p> 编辑 </p>
              <p> 删除 </p>
            </div>
            <div slot="reference" class="dian" @click.stop>...</div>
          </el-popover> -->
        </div>
        <div v-permission="['90002']" class="role-add" @click="addRoleFun">
          <i class="el-icon-circle-plus-outline" />新建角色
        </div>
      </div>
      <div v-permission="['90006']" class="role-right">
        <div v-if="labelType === 'emp'">
          <el-table :data="tableData" style="width: 100%" :header-cell-style="{background:'#F7F8FA'}">
            <el-table-column prop="name" align="center" label="员工姓名" />
            <el-table-column prop="department.department_name" align="center" label="所属部门" />
            <el-table-column prop="position" align="center" label="岗位" />
            <el-table-column prop="status" align="center" label="状态" />
            <el-table-column prop="" align="center" label="角色">
              <template slot-scope="scope">
                <span> {{ scope.row.roles.map((item) => item.name).join(',') }} </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="120">
              <template slot-scope="scope">
                <el-button v-permission="['90005']" type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="broadfun_block">
            <el-pagination
              :current-page="searchValue.pagenum"
              :page-sizes="[10, 20, 50]"
              :page-size="searchValue.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        <div v-else class="role-container">
          <h3> {{ activeType }} </h3>
          <div class="role-content">
            <div v-for="item in roleData" :key="item.ID">
              <h4> {{ item.name }} </h4>
              <div>
                <el-checkbox v-for="check in item.functions" :key="check.ID" v-model="check.enabled" :label="check.name" @change="checkChangeFun(check)"> {{ check.name }} </el-checkbox>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <AddRoleFrom :id="editId" ref="AddRoleFrom" :form="editFrom" :visible="visible" @close="closeFun" @success="successFun" />
    <AddRoleEmpFrom :id="empId" ref="AddRoleFrom" :name="empName" :list="EmpFromCheckList" :visible="empVisible" @close="empVisible = false" @success="successEmpFun" />
  </div>
</template>

<script>
import AddRoleFrom from './components/AddRoleFrom.vue'
import AddRoleEmpFrom from './components/AddRoleEmpFrom.vue'
import { getRoleList, getFunctionList, addFunction, deleteFunction, delRole, getRoleEmp } from '@/api/role'
export default {
  name: 'RoleIndex',
  components: {
    AddRoleFrom,
    AddRoleEmpFrom
  },
  data() {
    return {
      loading: false,
      visible: false,
      empVisible: false,
      editId: 0,
      editFrom: {},
      tableData: [],
      labelType: 'emp',
      activeType: '',
      roleId: 0,
      roleData: [],
      roleTypeArr: [],
      total: 0,
      searchValue: {
        pagenum: 1,
        pagesize: 10,
        name: ''
      },
      EmpFromCheckList: [],
      empId: 0,
      empName: ''
    }
  },
  async mounted() {
    this.init(true)
  },
  methods: {
    async init(first) {
      const res = await getRoleList()
      if (res.ret === 0) {
        this.roleTypeArr = res.data
        if (first) {
          this.activeType = res.data[0].name
          this.roleId = res.data[0].ID
          this.getRoleEmp()
        }
      }
    },
    async searchNameFun() {
      this.searchValue.pagenum = 1
      this.getRoleEmp()
    },
    async getRoleEmp() {
      this.loading = true
      try {
        const prams = { ...this.searchValue, role_id: this.roleId }
        const res = await getRoleEmp(prams)
        if (res.ret === 0) {
          this.tableData = res.data.list
          this.total = res.data.total
        }
      } catch (error) {
        this.loading = false
      } finally {
        this.loading = false
      }
    },
    async getFunctionList() {
      this.loading = true
      try {
        const res = await getFunctionList(this.roleId)
        if (res.ret === 0) {
          this.roleData = res.data
        }
      } catch (error) {
        this.loading = false
      } finally {
        this.loading = false
      }
    },
    beforeHandleCommand(command, item) {
      return {
        'command': command,
        item
      }
    },
    async handleCommand(command) {
      if (command.command === 'edit') {
        this.editId = command.item.ID
        this.editFrom = JSON.parse(JSON.stringify(command.item))
        this.visible = true
      } else {
        const row = command.item
        const isDelete = await this.$confirm(`确定删除 ${row.name} 角色吗？`, '提示', { type: 'warning' })
        if (!isDelete) {
          return
        }
        const res = await delRole(row.ID)
        if (res.ret === 0) {
          this.$message.success('删除成功')
          this.init()
        }
      }
    },
    async checkChangeFun(functin) {
      // 添加功能
      if (functin.enabled) {
        const res = await addFunction(this.roleId, functin.ID)
        if (res.ret === 0) {
          console.log(res)
        }
      } else {
        const res = await deleteFunction(this.roleId, functin.ID)
        if (res.ret === 0) {
          console.log(res)
        }
      }
    },
    changeRoleTypeFun(item) {
      this.activeType = item.name
      this.roleId = item.ID
      if (this.labelType === 'emp') {
        this.searchValue = {
          pagenum: 1,
          pagesize: 10,
          name: ''
        }

        this.getRoleEmp()
      } else {
        this.getFunctionList()
      }
    },
    changeLabelTypeFun(type) {
      this.labelType = type
      if (type === 'fun') {
        this.getFunctionList()
      } else {
        this.getRoleEmp()
      }
    },
    handleEdit(row) {
      this.empId = row.ID
      this.empName = row.name
      this.EmpFromCheckList = row.roles.map((item) => item.ID)
      console.log(this.empId)
      console.log(this.EmpFromCheckList)
      this.empVisible = true
    },
    addRoleFun() {
      this.editId = 0
      this.visible = true
    },
    addEmpFun() {
      this.empId = 0
      this.EmpFromCheckList = []
      this.empVisible = true
    },
    closeFun() {
      this.visible = false
    },
    successFun() {
      this.visible = false
      this.init()
    },
    successEmpFun() {
      this.empVisible = false
      this.getRoleEmp()
    },
    handleSizeChange(val) {
      this.searchValue.pagenum = 1
      this.searchValue.pagesize = val
      this.getRoleEmp()
    },
    handleCurrentChange(val) {
      this.searchValue.pagenum = val
      this.getRoleEmp()
    }
  }
}
</script>
<style lang="scss">
.popper-class {
  min-width: 80px;
}
.popper-p:hover {
  cursor: pointer;
}
</style>
<style lang="scss" scoped>
.role-container {
  .role-content {
    display: flex;
    margin-top: 10px;
    .role-left {
      width: 120px;
      height: calc(100vh - 142px);
      border-right: 1px solid #dddbdb;
      display: flex;
      flex-direction: column;
      .role-type {
        display: flex;
        align-items: center;
        height: 40px;
        width: 119px;
        color: #909399;
        padding-left: 20px;
        font-size: 14px;
        .name {
          flex: 1;
          height: 40px;
          line-height: 40px;
        }
        .dian {
          font-size: 24px;
          margin-top: -12px;
          color: #333;
          padding-right: 10px;
          display: none;
        }
      }
      .role-type:hover {
        cursor: pointer;
        .dian {
          display: block;
        }
      }
      .role-add {
        height: 40px;
        display: flex;
        align-items: center;
        padding-left: 16px;
        margin-top: 5px;
        color: #409EFF;
        font-size: 14px;
        i {
          margin-right: 3px;
        }
      }
      .role-add:hover {
        cursor: pointer;
      }
      .active {
        background-color: #EFF7FF;
      }
    }
    .role-right {
      flex: 1;
      height: calc(100vh - 142px);
      overflow-y: auto;
      padding: 0 10px;
      .role-container {
        .role-content {
          display: flex;
          flex-direction: column;
        }
      }
    }
  }
}
.role-tag {
  border-radius: 0;
}
.role-tag:hover {
  cursor: pointer;
}
.role-right::-webkit-scrollbar-track-piece { //滚动条凹槽的颜色，还可以设置边框属性
  background-color:#f8f8f8;
}
.role-right::-webkit-scrollbar {//滚动条的宽度
  width:9px;
  height:9px;
}
.role-right::-webkit-scrollbar-thumb {//滚动条的设置
  background-color:#dddddd;
  background-clip:padding-box;
  min-height:28px;
}
.role-right::-webkit-scrollbar-thumb:hover {
  background-color:#bbb;
}
.popper-class {
  min-width: 80px;
}
</style>
